package com.ymx.darling.session.map;

import com.ymx.darling.bean.entity.FieldInfo;
import com.ymx.darling.exception.DarlingException;
import com.ymx.darling.exception.ExceptionFactory;
import com.ymx.darling.util.ReflectUtil;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author 爱java的小于
 */
public class MapConvertHandlerMpl implements MapConvertHandler{
    @Override
    public <K, V> Map<K, V> convertToMapFromListByFieldName(List<V> elemList, FieldInfo fieldInfo) {
        if(elemList == null || elemList.isEmpty()){
            return new HashMap<>();
        }else{
            Map<K,V> reMap = new HashMap<>(elemList.size());
            Iterator<V> iterator = elemList.iterator();
            Field field = fieldInfo.getField();
            while(iterator.hasNext()){
                Object tmp = iterator.next();
                reMap.put(ReflectUtil.getValue(field, tmp),(V)tmp);
            }
            //返回Map
            return reMap;
        }
    }


    @Override
    public <K, V> Map<K, V> convertToMapFromList(List<V> elemList, String keyName) {
        if(elemList == null || elemList.isEmpty()){
            return new HashMap<>();
        }else{
            List<Map<String,Object>> list = (List<Map<String,Object>>)elemList;
            if(!(list.get(0).containsKey(keyName))){
                throw ExceptionFactory.wrapException("List转为Map时抛出异常", new DarlingException("字段:"+keyName+"在结果集中不存在"));
            }else{
                Map<Object,Map<String,Object>> reMap = new HashMap<>(elemList.size());
                for (Map<String, Object> tmp : list) {;
                    reMap.put(tmp.get(keyName),tmp);
                }
                return (Map<K, V>) reMap;
            }
        }
    }

}
